import React, { PureComponent } from 'react'
import { connect, } from 'react-redux';
import { BackHandler, View, StatusBar } from 'react-native';

import {
  NavigationActions
} from 'react-navigation';

import { MainNavigator } from './navigator/MainNavigator';
import SplashScreen from 'react-native-splash-screen';

export function routerReducer(state, action = {}) {
  return MainNavigator.router.getStateForAction(action, state)
}


function getCurrentScreen(navigationState) {

  if (!navigationState) {
    return null
  }
  const route = navigationState.routes[navigationState.index]
  if (route.routes) {
    return getCurrentScreen(route)
  }
  return route.routeName
}


@connect(({ router }) => ({ router }))
class Router extends PureComponent {
  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.backHandle)
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandle)
  }

  backHandle = () => {
    const currentScreen = getCurrentScreen(this.props.router)
    if (currentScreen === 'Login') {
      return true
    }
    if (currentScreen !== 'Home') {
      this.props.dispatch(NavigationActions.back())
      return true
    }
    return false
  }
  componentDidMount() {
    SplashScreen.hide();//关闭启动屏幕
  }
  render() {
    const { dispatch, router, navigation } = this.props

    return (
      <View style={{ width: '100%', height: '100%' }}>
        <StatusBar backgroundColor="#fff" />
        <MainNavigator navigation={navigation} />
      </View>
    )
  }
}


export default Router;
